package utils

import (
	"time"
	"github.com/wanhuo/GoSocketFrame/common"
)

type Ticker struct {
	duration time.Duration
	userData int
	exit     chan int
	itimer   common.ITimer
	log      *Logger
	tticker  *time.Ticker
	repeat   bool
	first    bool
}

func NewTicker(itimer common.ITimer, dur time.Duration, repeat bool, callback int) *Ticker {
	return &Ticker{
		itimer:   itimer,
		duration: dur,
		repeat:   repeat,
		userData: callback,
		exit:     make(chan int),
		first:    true,
		log:      NewLogger(),
	}
}

func (self *Ticker) startTick() {
	go func() {
		for {
			select {
			case <-self.tticker.C:
				go self.itimer.OnTimer(self.userData)
				if !self.repeat {
					self.tticker.Stop()
				}
			case <-self.exit:
				break
			}
			time.Sleep(10 * time.Millisecond)
		}
	}()
}

func (self *Ticker) Start() {
	self.Stop()

	self.tticker = time.NewTicker(self.duration)
	if self.first {
		self.startTick()
		self.first = false
	}
}

func (self *Ticker) Stop() {
	if self.tticker != nil {
		self.tticker.Stop()
		self.exit <- 0
	}
}

//设置定时间隔并启动
func (self *Ticker) StartDuration(dur time.Duration) {
	self.Stop()

	self.duration = dur
	self.tticker = time.NewTicker(self.duration)
	if self.first {
		self.startTick()
		self.first = false
	}
}